# /usr/bin/python
# -*- coding: utf-8 -*-

import os,sys
BASE_DIR = os.path.dirname(os.path.abspath(os.curdir))
sys.path.append(BASE_DIR)
from models.MySQL import MySQL
from conf.setting import templates 
from util.log import get_stream_logger


def add_template():
    logger = get_stream_logger("add_template")

    with MySQL() as cur:
        for template in templates:
            check_cmd = "SELECT * FROM tpl WHERE tpl_name=%s"%template
            check_res = cur.cur.execute(check_cmd)
            if check_res == 0:
                insert_cmd = "INSERT INTO tpl VALUES (null,'%s',0,1,'root',null)"%template
                res = cur.update(insert_cmd)
                if res != 1:
                    logger.info("Template %s insert failed"%template)

def add_hosts():
    logger = get_stream_logger("add_hosts")

    Z = ZBX()
    hosts = Z.get_host(host="")

    with MySQL() as cur:
        for host in hosts:
            name = host["name"]
            hostid = host["hostid"]

            interfaces = Z.get_interface(hostids=hostid)
            for interface in interfaces:
                if interface["main"] == "1":
                    ip = interface["ip"]
            
            with MySQL() as cur:
                check_cmd = "SELECT * FROM host WHERE hostname='%s' AND ip='%s'"%(name,ip)
                check_res = cur.cur.execute(check_cmd)
                if check_res == 0:
                    insert_cmd = "INSERT INTO host VALUES (null,'{hostname}','{ip}','','','0','0',null)".format(
                        hostname=name, ip=ip
                    )
                    res = cur.update(insert_cmd)
                    if res != 1:
                        logger.error("Insert into host:%s , %s failed"%(name,ip))

def add_groups():
    logger = get_stream_logger("add_hostgroup")

    Z = ZBX()
    groups = Z.get_group(name='')

    with MySQL() as cur:
        for group in groups:
            check_cmd = "SELECT * FROM grp WHERE grp_name='%s'"%group["name"]
            check_res = cur.cur.execute(check_cmd)
            if check_res == 0:
                insert_cmd = "INSERT INTO grp VALUES (null,'%s','root',null,'0')"%group["name"]
                res = cur.update(insert_cmd)
                if res !=1:
                    logger.error("Insert into grp: %s "%group["name"])

    
